package com.gopay.checkorder.service.task;

import com.gopay.common.Result;
import com.gopay.common.domain.bank.yspay.expay.pay.YspayAdPayMessage;
import com.gopay.common.util.DateUtils;
import com.gopay.common.util.SendMail;
import com.gopay.remote.bank.AdjustInteractRemoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 银盛代扣下载对账文件
 *
 * @author wangxintao
 * @YspayAdDownloadOrderTaskImpl.java
 */
public class YspayAdDownloadOrderTaskImpl implements Task {
    private final static Logger logger = LoggerFactory.getLogger("CHECK_ORDER");

    @Resource(name = "yspayadpayConfig")
    private Map<String, String> yspayadpayConfig;

    @Resource(name = "bankAdjustClient")
    private AdjustInteractRemoteService bankAdjustClient;

    @Override
    public void doTask() {
        // 对账单文件名格式：yspayadjust-20160530.txt
        // 对账单文件夹：/usr/local/ciecc/bankFiles/YSPAY/
        // 1.检查文件夹里是否已有昨天对账单文件
        // 2.如果没有则接口查对账单
        // 3.将对账单形成文件放在文件夹里
        // 4.作为附件发送邮件
        logger.error("YspayAdDownloadOrderTaskImpl: 定时任务start ");
        try {
            if ("off".equals(yspayadpayConfig.get("mailSwitch"))) {
                logger.error("YspayAdDownloadOrderTaskImpl: 不进行操作直接返回!");
                return;
            }

            // 生成对账单文件所需参数
            String locpath = yspayadpayConfig.get("locpath");
            String fTime = DateUtils.getYesterday();
            
            String fName = "yspayadjust-" + fTime + ".txt";
            List sendFile = new ArrayList();
            List names = new ArrayList();
            String messageText = "";

            // 判断本地服务器是否存在代扣对账文件
            if (!(new File(locpath + fName).exists())) {
                // 如果不存在对账文件，查对账单并生成文件
                String content = getYspayadjust();
                boolean flag = string2File(content, locpath+fName);
                if (flag) {
                    names.add(fName);
                    logger.error("YspayAdDownloadOrderTaskImpl " + fName + " 对账文件生成成功!");
                } else {
                    logger.error("YspayAdDownloadOrderTaskImpl " + fName + " 对账文件生成失败!");
                    return;
                }
            } else {
                logger.error("YspayAdDownloadOrderTaskImpl " + fName + " 对账文件已存在!");
            }

            // 若对账文件全部为空，则邮件内容标明
            if (names.size() < 1) {
                logger.error("YspayAdDownloadOrderTaskImpl: 银盛代扣对账文件为null或本地已成功下载!");
                return;
            } else {
                messageText = fTime + ": 银盛代扣对账文件见附件!" + fName;
                for (int i = 0; i < names.size(); i++) {
                    sendFile.add(locpath + (String) names.get(i));
                }
            }
            String subject = "银盛代扣对账文件";
            String[] cc = yspayadpayConfig.get("sendmail.cc").split(","); // 获取多个抄送人
            List ccList = Arrays.asList(cc);

            logger.error("sendMessage  config:--host:"+yspayadpayConfig.get("sendmail.host")+"----sender:"+yspayadpayConfig.get("sendmail.sender")
            +"----username:"+yspayadpayConfig.get("sendmail.username")+"----password:"+yspayadpayConfig.get("sendmail.password")
            +"----receiver:"+ yspayadpayConfig.get("sendmail.receiver"));
            // 发送邮件
            SendMail.sendMessage(yspayadpayConfig.get("sendmail.host"), yspayadpayConfig.get("sendmail.sender"),
                    yspayadpayConfig.get("sendmail.username"), yspayadpayConfig.get("sendmail.password"),
                    yspayadpayConfig.get("sendmail.receiver"), subject, messageText, "text/html;charset=gb2312", ccList,
                    sendFile, names);
            logger.error("------银盛代扣发送邮件成功--------");
            
        } catch (Exception e) {
            logger.error("YspayAdDownloadOrderTaskImpl error: ", e);
        }
    }

    /**
     * 接口查对账单
     *
     * @return
     */
    private String getYspayadjust() {
        YspayAdPayMessage message = new YspayAdPayMessage();
        message.setAccountDate(DateUtils.getYesterday());
        Result result = bankAdjustClient.adjust(message);
        message = (YspayAdPayMessage) result.getDefaultModel();
        return message.getAdjustContent();
    }

    /**
     * 生成数据文件
     *
     * @param filePath 写入文件的路径
     * @param content  写入的字符串内容
     * @return
     */
    public boolean string2File(String content, String filePath) {
        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter;
        boolean flag = true;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            bufferedReader = new BufferedReader(new StringReader(content));
            bufferedWriter = new BufferedWriter(new FileWriter(file));
            char buffer[] = new char[1024];
            int len;
            while ((len = bufferedReader.read(buffer)) != -1) {
                bufferedWriter.write(buffer, 0, len);
            }
            bufferedWriter.flush();
            bufferedReader.close();
            bufferedWriter.close();
        } catch (IOException e) {
            logger.error(String.valueOf(e));
            flag = false;
            return flag;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    logger.error(String.valueOf(e));
                }
            }
        }
        return flag;
    }
}
